package com.qxkj.mysql.multidb.dbRoute.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * Copyright © 2018年 ziniuxiaozhu. All rights reserved.
 *
 * @Author 临江仙 hzqiuxm@163.com
 * TODO:亲爱的临江仙，请写点注释吧...........
 * @Date 2018/9/5 11:04
 */
@Configuration
@MapperScan(basePackages = "com.qxkj.mysql.multidb.demp.dao", sqlSessionTemplateRef = "sqlSessionFactory2")
public class DsConfig2 {

    @Bean
    @ConfigurationProperties(prefix ="app.datasource.third")
    public DataSourceProperties dataSourceProperties2() {
        return new DataSourceProperties();
    }

    @Bean(name = "dataSource2")
    @ConfigurationProperties(prefix = "app.datasource.third")
    public DataSource dataSource2(){
        return dataSourceProperties2().initializeDataSourceBuilder().build();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory2() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource2());
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2());
        return template;
    }

    @Bean(name = "dataTransactionManager2")
    public DataSourceTransactionManager dataTransactionManager2() {
        return new DataSourceTransactionManager(dataSource2());
    }


}
